Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [4]:
# TODO: Make all necessary imports.
import warnings
warnings.filterwarnings('ignore')

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import numpy as np
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()

import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)

print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 tf.keras version:', tf.keras.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')
Using:
	• TensorFlow version: 2.0.0
	• tf.keras version: 2.2.4-tf
	• Running on GPU

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [5]:
# TODO: Load the dataset with TensorFlow Datasets.
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
# TODO: Create a training set, a validation set and a test set.

train, test, validation = dataset['train'], dataset['test'], dataset['validation']

dataset_info
WARNING:absl:Warning: Setting shuffle_files=True because split=TRAIN and shuffle_files=None. This behavior will be deprecated on 2019-08-06, at which point shuffle_files=False will be the default for all splits.
Out[5]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    version=0.0.1,
    description='
The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
in the United Kingdom. Each class consists of between 40 and 258 images. The images have
large scale, pose and light variations. In addition, there are categories that have large
variations within the category and several very similar categories.

The dataset is divided into a training set, a validation set and a test set.
The training set and validation set each consist of 10 images per class (totalling 1030 images each).
The test set consist of the remaining 6129 images (minimum 20 per class).
',
    urls=['https://www.robots.ox.ac.uk/~vgg/data/flowers/102/'],
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    total_num_examples=8189,
    splits={
        'test': 6149,
        'train': 1020,
        'validation': 1020,
    },
    supervised_keys=('image', 'label'),
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
    redistribution_info=,
)

Explore the Dataset

In [6]:
# TODO: Get the number of examples in each set from the dataset info.

print('Number of examples in Training Set:',dataset_info.splits['train'].num_examples)
print('Number of examples in Testing Set:',dataset_info.splits['test'].num_examples)
print('Number of examples in Validation Set:',dataset_info.splits['validation'].num_examples)
# TODO: Get the number of classes in the dataset from the dataset info.
print('Number of classes in our dataset:', dataset_info.features['label'].num_classes)
Number of examples in Training Set: 1020
Number of examples in Testing Set: 6149
Number of examples in Validation Set: 1020
Number of classes in our dataset: 102
In [7]:
dataset_info.features['image']
Out[7]:
Image(shape=(None, None, 3), dtype=tf.uint8)
In [8]:
# # taken from dataset source code _NAME
# class_names = [
#     "pink primrose", "hard-leaved pocket orchid", "canterbury bells",
#     "sweet pea", "english marigold", "tiger lily", "moon orchid",
#     "bird of paradise", "monkshood", "globe thistle", "snapdragon",
#     "colt's foot", "king protea", "spear thistle", "yellow iris",
#     "globe-flower", "purple coneflower", "peruvian lily", "balloon flower",
#     "giant white arum lily", "fire lily", "pincushion flower", "fritillary",
#     "red ginger", "grape hyacinth", "corn poppy", "prince of wales feathers",
#     "stemless gentian", "artichoke", "sweet william", "carnation",
#     "garden phlox", "love in the mist", "mexican aster", "alpine sea holly",
#     "ruby-lipped cattleya", "cape flower", "great masterwort", "siam tulip",
#     "lenten rose", "barbeton daisy", "daffodil", "sword lily", "poinsettia",
#     "bolero deep blue", "wallflower", "marigold", "buttercup", "oxeye daisy",
#     "common dandelion", "petunia", "wild pansy", "primula", "sunflower",
#     "pelargonium", "bishop of llandaff", "gaura", "geranium", "orange dahlia",
#     "pink-yellow dahlia?", "cautleya spicata", "japanese anemone",
#     "black-eyed susan", "silverbush", "californian poppy", "osteospermum",
#     "spring crocus", "bearded iris", "windflower", "tree poppy", "gazania",
#     "azalea", "water lily", "rose", "thorn apple", "morning glory",
#     "passion flower", "lotus", "toad lily", "anthurium", "frangipani",
#     "clematis", "hibiscus", "columbine", "desert-rose", "tree mallow",
#     "magnolia", "cyclamen", "watercress", "canna lily", "hippeastrum",
#     "bee balm", "ball moss", "foxglove", "bougainvillea", "camellia", "mallow",
#     "mexican petunia", "bromelia", "blanket flower", "trumpet creeper",
#     "blackberry lily"
# ]
In [9]:
import json

with open('label_map.json') as f:
    class_names = json.load(f)

print(class_names)
{'21': 'fire lily', '3': 'canterbury bells', '45': 'bolero deep blue', '1': 'pink primrose', '34': 'mexican aster', '27': 'prince of wales feathers', '7': 'moon orchid', '16': 'globe-flower', '25': 'grape hyacinth', '26': 'corn poppy', '79': 'toad lily', '39': 'siam tulip', '24': 'red ginger', '67': 'spring crocus', '35': 'alpine sea holly', '32': 'garden phlox', '10': 'globe thistle', '6': 'tiger lily', '93': 'ball moss', '33': 'love in the mist', '9': 'monkshood', '102': 'blackberry lily', '14': 'spear thistle', '19': 'balloon flower', '100': 'blanket flower', '13': 'king protea', '49': 'oxeye daisy', '15': 'yellow iris', '61': 'cautleya spicata', '31': 'carnation', '64': 'silverbush', '68': 'bearded iris', '63': 'black-eyed susan', '69': 'windflower', '62': 'japanese anemone', '20': 'giant white arum lily', '38': 'great masterwort', '4': 'sweet pea', '86': 'tree mallow', '101': 'trumpet creeper', '42': 'daffodil', '22': 'pincushion flower', '2': 'hard-leaved pocket orchid', '54': 'sunflower', '66': 'osteospermum', '70': 'tree poppy', '85': 'desert-rose', '99': 'bromelia', '87': 'magnolia', '5': 'english marigold', '92': 'bee balm', '28': 'stemless gentian', '97': 'mallow', '57': 'gaura', '40': 'lenten rose', '47': 'marigold', '59': 'orange dahlia', '48': 'buttercup', '55': 'pelargonium', '36': 'ruby-lipped cattleya', '91': 'hippeastrum', '29': 'artichoke', '71': 'gazania', '90': 'canna lily', '18': 'peruvian lily', '98': 'mexican petunia', '8': 'bird of paradise', '30': 'sweet william', '17': 'purple coneflower', '52': 'wild pansy', '84': 'columbine', '12': "colt's foot", '11': 'snapdragon', '96': 'camellia', '23': 'fritillary', '50': 'common dandelion', '44': 'poinsettia', '53': 'primula', '72': 'azalea', '65': 'californian poppy', '80': 'anthurium', '76': 'morning glory', '37': 'cape flower', '56': 'bishop of llandaff', '60': 'pink-yellow dahlia', '82': 'clematis', '58': 'geranium', '75': 'thorn apple', '41': 'barbeton daisy', '95': 'bougainvillea', '43': 'sword lily', '83': 'hibiscus', '78': 'lotus lotus', '88': 'cyclamen', '94': 'foxglove', '81': 'frangipani', '74': 'rose', '89': 'watercress', '73': 'water lily', '46': 'wallflower', '77': 'passion flower', '51': 'petunia'}
In [10]:
labels_list = [j.numpy() for i,j in train]
print(f'Dataset labels range from  {min(labels_list)} - {max(labels_list)}')
Dataset labels range from  0 - 101
In [11]:
class_labels = [int(i) for i in class_names.keys()]
print(f'class_name range from  {min(class_labels)} - {max(class_labels)}')
class_name range from  1 - 102
In [12]:
# TODO: Print the shape and corresponding label of 3 images in the training set.

for image, label in train.take(3):
    plt.figure()
    image = image.numpy()
    label = label.numpy()
    plt.imshow(image, cmap= plt.cm.binary)
    plt.colorbar()
    print('The label of this image is:', label)
    print('The class name of this image is:', class_names[str(label+1)])

    plt.show()
The label of this image is: 52
The class name of this image is: primula
The label of this image is: 60
The class name of this image is: cautleya spicata
The label of this image is: 52
The class name of this image is: primula
In [13]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 
for image, label in train.take(1):
    plt.figure()
    image = image.numpy()
    label = label.numpy()
    plt.imshow(image, cmap= plt.cm.binary)
    plt.colorbar()
    print('The label of this image is:', label)
    print('The class name of this image is:', class_names[str(label+1)])

    plt.show()
The label of this image is: 52
The class name of this image is: primula

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [14]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [15]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in train.take(1):
    plt.figure()
    image = image.numpy()
    label = label.numpy()
    plt.imshow(image, cmap= plt.cm.binary)
    plt.colorbar()
    print('The label of this image is:', label)
    print('The class name of this image is:', class_names[str(label+1)])

    plt.show()
The label of this image is: 52
The class name of this image is: primula

Create Pipeline

In [16]:
# TODO: Create a pipeline for each set.
batch_size = 64
image_size = 224

def format_image(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size, image_size))
    image /= 255
    return image, label



num_training_examples = dataset_info.splits['train'].num_examples

training_batches = train.shuffle(num_training_examples//4).map(format_image).batch(batch_size).prefetch(1)
validation_batches = validation.map(format_image).batch(batch_size).prefetch(1)
testing_batches = test.map(format_image).batch(batch_size).prefetch(1)

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [17]:
!ls -lh
total 2.0M
drwxr-xr-x 2 root root 4.0K Oct  3  2019 assets
-rw-r--r-- 1 root root 2.2K Oct  3  2019 label_map.json
-rw-r--r-- 1 root root 2.0M Apr  4 09:21 Project_Image_Classifier_Project.ipynb
drwxr-xr-x 2 root root 4.0K Oct  3  2019 test_images
In [18]:
# TODO: Build and train your network.
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))
feature_extractor.trainable = False

model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(102, activation = 'softmax')
])

model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense (Dense)                (None, 102)               130662    
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
In [19]:
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

EPOCHS = 70

early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)

history = model.fit(training_batches,
                    epochs=EPOCHS,
                    validation_data=validation_batches,
                    callbacks=[early_stopping])
Epoch 1/70
16/16 [==============================] - 14s 893ms/step - loss: 4.5585 - accuracy: 0.0627 - val_loss: 0.0000e+00 - val_accuracy: 0.0000e+00
Epoch 2/70
16/16 [==============================] - 7s 410ms/step - loss: 2.8523 - accuracy: 0.5441 - val_loss: 2.6449 - val_accuracy: 0.5324
Epoch 3/70
16/16 [==============================] - 7s 409ms/step - loss: 1.7756 - accuracy: 0.8333 - val_loss: 2.0140 - val_accuracy: 0.6569
Epoch 4/70
16/16 [==============================] - 7s 407ms/step - loss: 1.1526 - accuracy: 0.9206 - val_loss: 1.6485 - val_accuracy: 0.7225
Epoch 5/70
16/16 [==============================] - 7s 408ms/step - loss: 0.7934 - accuracy: 0.9588 - val_loss: 1.4352 - val_accuracy: 0.7549
Epoch 6/70
16/16 [==============================] - 7s 412ms/step - loss: 0.5705 - accuracy: 0.9804 - val_loss: 1.2948 - val_accuracy: 0.7608
Epoch 7/70
16/16 [==============================] - 7s 410ms/step - loss: 0.4474 - accuracy: 0.9863 - val_loss: 1.1948 - val_accuracy: 0.7775
Epoch 8/70
16/16 [==============================] - 7s 409ms/step - loss: 0.3497 - accuracy: 0.9931 - val_loss: 1.1232 - val_accuracy: 0.7833
Epoch 9/70
16/16 [==============================] - 7s 410ms/step - loss: 0.2856 - accuracy: 0.9941 - val_loss: 1.0693 - val_accuracy: 0.7814
Epoch 10/70
16/16 [==============================] - 7s 409ms/step - loss: 0.2344 - accuracy: 0.9990 - val_loss: 1.0258 - val_accuracy: 0.7873
Epoch 11/70
16/16 [==============================] - 7s 411ms/step - loss: 0.1946 - accuracy: 0.9990 - val_loss: 0.9923 - val_accuracy: 0.7931
Epoch 12/70
16/16 [==============================] - 7s 416ms/step - loss: 0.1687 - accuracy: 0.9990 - val_loss: 0.9645 - val_accuracy: 0.7882
Epoch 13/70
16/16 [==============================] - 7s 432ms/step - loss: 0.1431 - accuracy: 0.9990 - val_loss: 0.9393 - val_accuracy: 0.7922
Epoch 14/70
16/16 [==============================] - 7s 412ms/step - loss: 0.1268 - accuracy: 1.0000 - val_loss: 0.9179 - val_accuracy: 0.7951
Epoch 15/70
16/16 [==============================] - 7s 410ms/step - loss: 0.1121 - accuracy: 1.0000 - val_loss: 0.9017 - val_accuracy: 0.8000
Epoch 16/70
16/16 [==============================] - 7s 407ms/step - loss: 0.0988 - accuracy: 1.0000 - val_loss: 0.8849 - val_accuracy: 0.7990
Epoch 17/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0887 - accuracy: 1.0000 - val_loss: 0.8708 - val_accuracy: 0.8059
Epoch 18/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0796 - accuracy: 1.0000 - val_loss: 0.8581 - val_accuracy: 0.8078
Epoch 19/70
16/16 [==============================] - 7s 409ms/step - loss: 0.0727 - accuracy: 1.0000 - val_loss: 0.8489 - val_accuracy: 0.8069
Epoch 20/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0668 - accuracy: 1.0000 - val_loss: 0.8387 - val_accuracy: 0.8098
Epoch 21/70
16/16 [==============================] - 7s 413ms/step - loss: 0.0613 - accuracy: 1.0000 - val_loss: 0.8287 - val_accuracy: 0.8088
Epoch 22/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0561 - accuracy: 1.0000 - val_loss: 0.8204 - val_accuracy: 0.8088
Epoch 23/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0522 - accuracy: 1.0000 - val_loss: 0.8134 - val_accuracy: 0.8088
Epoch 24/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0484 - accuracy: 1.0000 - val_loss: 0.8070 - val_accuracy: 0.8108
Epoch 25/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0455 - accuracy: 1.0000 - val_loss: 0.8005 - val_accuracy: 0.8118
Epoch 26/70
16/16 [==============================] - 7s 412ms/step - loss: 0.0424 - accuracy: 1.0000 - val_loss: 0.7951 - val_accuracy: 0.8108
Epoch 27/70
16/16 [==============================] - 7s 413ms/step - loss: 0.0393 - accuracy: 1.0000 - val_loss: 0.7887 - val_accuracy: 0.8088
Epoch 28/70
16/16 [==============================] - 7s 412ms/step - loss: 0.0377 - accuracy: 1.0000 - val_loss: 0.7831 - val_accuracy: 0.8108
Epoch 29/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0352 - accuracy: 1.0000 - val_loss: 0.7792 - val_accuracy: 0.8127
Epoch 30/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0338 - accuracy: 1.0000 - val_loss: 0.7748 - val_accuracy: 0.8118
Epoch 31/70
16/16 [==============================] - 7s 414ms/step - loss: 0.0318 - accuracy: 1.0000 - val_loss: 0.7700 - val_accuracy: 0.8098
Epoch 32/70
16/16 [==============================] - 7s 423ms/step - loss: 0.0303 - accuracy: 1.0000 - val_loss: 0.7661 - val_accuracy: 0.8108
Epoch 33/70
16/16 [==============================] - 7s 412ms/step - loss: 0.0287 - accuracy: 1.0000 - val_loss: 0.7628 - val_accuracy: 0.8118
Epoch 34/70
16/16 [==============================] - 6s 406ms/step - loss: 0.0270 - accuracy: 1.0000 - val_loss: 0.7592 - val_accuracy: 0.8118
Epoch 35/70
16/16 [==============================] - 7s 414ms/step - loss: 0.0255 - accuracy: 1.0000 - val_loss: 0.7560 - val_accuracy: 0.8108
Epoch 36/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0245 - accuracy: 1.0000 - val_loss: 0.7525 - val_accuracy: 0.8127
Epoch 37/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0235 - accuracy: 1.0000 - val_loss: 0.7496 - val_accuracy: 0.8118
Epoch 38/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0223 - accuracy: 1.0000 - val_loss: 0.7465 - val_accuracy: 0.8157
Epoch 39/70
16/16 [==============================] - 7s 409ms/step - loss: 0.0216 - accuracy: 1.0000 - val_loss: 0.7437 - val_accuracy: 0.8157
Epoch 40/70
16/16 [==============================] - 7s 409ms/step - loss: 0.0207 - accuracy: 1.0000 - val_loss: 0.7413 - val_accuracy: 0.8157
Epoch 41/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0199 - accuracy: 1.0000 - val_loss: 0.7383 - val_accuracy: 0.8167
Epoch 42/70
16/16 [==============================] - 7s 409ms/step - loss: 0.0192 - accuracy: 1.0000 - val_loss: 0.7368 - val_accuracy: 0.8137
Epoch 43/70
16/16 [==============================] - 7s 412ms/step - loss: 0.0184 - accuracy: 1.0000 - val_loss: 0.7340 - val_accuracy: 0.8167
Epoch 44/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0177 - accuracy: 1.0000 - val_loss: 0.7322 - val_accuracy: 0.8167
Epoch 45/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.7302 - val_accuracy: 0.8167
Epoch 46/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0164 - accuracy: 1.0000 - val_loss: 0.7274 - val_accuracy: 0.8176
Epoch 47/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0158 - accuracy: 1.0000 - val_loss: 0.7252 - val_accuracy: 0.8167
Epoch 48/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0155 - accuracy: 1.0000 - val_loss: 0.7240 - val_accuracy: 0.8176
Epoch 49/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0148 - accuracy: 1.0000 - val_loss: 0.7223 - val_accuracy: 0.8167
Epoch 50/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0144 - accuracy: 1.0000 - val_loss: 0.7207 - val_accuracy: 0.8167
Epoch 51/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.7190 - val_accuracy: 0.8176
Epoch 52/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0135 - accuracy: 1.0000 - val_loss: 0.7171 - val_accuracy: 0.8157
Epoch 53/70
16/16 [==============================] - 7s 407ms/step - loss: 0.0131 - accuracy: 1.0000 - val_loss: 0.7154 - val_accuracy: 0.8176
Epoch 54/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0126 - accuracy: 1.0000 - val_loss: 0.7141 - val_accuracy: 0.8167
Epoch 55/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0123 - accuracy: 1.0000 - val_loss: 0.7128 - val_accuracy: 0.8167
Epoch 56/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0118 - accuracy: 1.0000 - val_loss: 0.7113 - val_accuracy: 0.8176
Epoch 57/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0113 - accuracy: 1.0000 - val_loss: 0.7101 - val_accuracy: 0.8176
Epoch 58/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0111 - accuracy: 1.0000 - val_loss: 0.7087 - val_accuracy: 0.8176
Epoch 59/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0110 - accuracy: 1.0000 - val_loss: 0.7074 - val_accuracy: 0.8186
Epoch 60/70
16/16 [==============================] - 7s 431ms/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.7059 - val_accuracy: 0.8196
Epoch 61/70
16/16 [==============================] - 7s 420ms/step - loss: 0.0104 - accuracy: 1.0000 - val_loss: 0.7049 - val_accuracy: 0.8196
Epoch 62/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0101 - accuracy: 1.0000 - val_loss: 0.7040 - val_accuracy: 0.8186
Epoch 63/70
16/16 [==============================] - 7s 411ms/step - loss: 0.0098 - accuracy: 1.0000 - val_loss: 0.7027 - val_accuracy: 0.8186
Epoch 64/70
16/16 [==============================] - 6s 406ms/step - loss: 0.0094 - accuracy: 1.0000 - val_loss: 0.7016 - val_accuracy: 0.8186
Epoch 65/70
16/16 [==============================] - 7s 409ms/step - loss: 0.0093 - accuracy: 1.0000 - val_loss: 0.7007 - val_accuracy: 0.8196
Epoch 66/70
16/16 [==============================] - 7s 407ms/step - loss: 0.0091 - accuracy: 1.0000 - val_loss: 0.6996 - val_accuracy: 0.8206
Epoch 67/70
16/16 [==============================] - 7s 408ms/step - loss: 0.0089 - accuracy: 1.0000 - val_loss: 0.6984 - val_accuracy: 0.8206
Epoch 68/70
16/16 [==============================] - 6s 405ms/step - loss: 0.0086 - accuracy: 1.0000 - val_loss: 0.6975 - val_accuracy: 0.8206
Epoch 69/70
16/16 [==============================] - 7s 410ms/step - loss: 0.0084 - accuracy: 1.0000 - val_loss: 0.6965 - val_accuracy: 0.8206
Epoch 70/70
16/16 [==============================] - 7s 407ms/step - loss: 0.0082 - accuracy: 1.0000 - val_loss: 0.6954 - val_accuracy: 0.8186
In [23]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(len(training_accuracy))

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [24]:
# TODO: Print the loss and accuracy values achieved on the entire test set.

result = model.evaluate(testing_batches)
print(f'Test loss {result[0]} and Test accuracy {result[1]}')
97/97 [==============================] - 19s 195ms/step - loss: 0.8242 - accuracy: 0.7887
Test loss 0.8242134587051942 and Test accuracy 0.7887461185455322

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [35]:
# TODO: Save your trained model as a Keras model.
model.save('./oxford_flower_1.h5')
In [36]:
!ls -lh
total 23M
drwxr-xr-x 2 root root 4.0K Oct  3  2019 assets
-rw-r--r-- 1 root root 2.2K Oct  3  2019 label_map.json
-rw-r--r-- 1 root root  11M Apr  4 09:33 oxford_flower_1.h5
-rw-r--r-- 1 root root  11M Apr  4 09:31 oxford_flower.h5
-rw-r--r-- 1 root root 2.0M Apr  4 09:33 Project_Image_Classifier_Project.ipynb
drwxr-xr-x 2 root root 4.0K Oct  3  2019 test_images

Load the Keras Model

Load the Keras model you saved above.

In [38]:
# TODO: Load the Keras model
reloaded_model = tf.keras.models.load_model('oxford_flower_1.h5', custom_objects={'KerasLayer':hub.KerasLayer})
In [39]:
reloaded_model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense (Dense)                (None, 102)               130662    
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [54]:
# TODO: Create the process_image function
def process_image(image):
#     print(type(image))
    ts_img = tf.convert_to_tensor(image)
#     print(type(ts_img))
    ts_img = tf.image.resize(ts_img, (224,224))
    ts_img /= 255
    return ts_img.numpy()

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [55]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [217]:
# TODO: Create the predict function
def predict(image_path, model, n):
    img = Image.open(image_path)
    test_image = np.asarray(img)
    processed_img = process_image(test_image)
    processed_img = np.expand_dims(processed_img, axis=0)
#     print(processed_img.shape)
    prediction = model.predict(processed_img)
#     print(prediction[0].argsort())
    idx = prediction[0].argsort()[-n:][::-1]
    labels = [str(i) for i in idx]
    probs = (prediction[0][idx])
    return probs, labels
In [224]:
# Testing
probs, classes = predict('./test_images/hard-leaved_pocket_orchid.jpg', reloaded_model, 5)
print(probs)
print(classes)

for i in classes:
    print(class_names[str(int(i)+1)])
[9.9785358e-01 3.6313914e-04 2.7600242e-04 2.7013363e-04 2.5531431e-04]
['1', '79', '6', '67', '5']
hard-leaved pocket orchid
anthurium
moon orchid
bearded iris
tiger lily
In [226]:
# Testing
probs, classes = predict('./test_images/orange_dahlia.jpg', reloaded_model, 5)
print(probs)
print(classes)

for i in classes:
    print(class_names[str(int(i)+1)])
[0.46421385 0.27870446 0.06784321 0.04333372 0.04324402]
['58', '4', '70', '65', '99']
orange dahlia
english marigold
gazania
osteospermum
blanket flower
In [227]:
# Testing
probs, classes = predict('./test_images/wild_pansy.jpg', reloaded_model, 5)
print(probs)
print(classes)

for i in classes:
    print(class_names[str(int(i)+1)])
[9.9884206e-01 2.3008214e-04 2.1038171e-04 1.5372710e-04 1.3852360e-04]
['51', '18', '63', '33', '81']
wild pansy
balloon flower
silverbush
mexican aster
clematis

Testing the Model overall

In [191]:
cc = []
for i, l in testing_batches.take(1):
    p = model.predict(i)
    images = i.numpy().squeeze()
    labels = l.numpy()
    cc.append(labels)
In [223]:
plt.figure(figsize=(10,15))

for n in range(30):
    plt.subplot(6,5,n+1)
    plt.imshow(images[n], cmap = plt.cm.binary)
    color = 'green' if np.argmax(p[n]) == labels[n] else 'red'
    plt.title(class_names[str(np.argmax(p[n]+1))], color=color)
    plt.axis('off')

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [272]:
import os
for file in os.listdir('./test_images/'):
    probs, classes = predict(f'./test_images/{file}', reloaded_model, 5)
    guessed_classes = [class_names[str(int(i)+1)] for i in classes ]
    print(guessed_classes)

    image_path = f'./test_images/{file}'
    im = Image.open(image_path)
    test_image = np.asarray(im)

    processed_test_image = process_image(test_image)

    fig, (ax1, ax2) = plt.subplots(figsize=(10,12), ncols=2)
    ax1.imshow(processed_test_image, cmap = plt.cm.binary)
    ax1.axis('off')
    ax1.set_title(guessed_classes[0])
    ax2.barh(np.arange(5), probs)
    ax2.set_aspect(0.1)
    ax2.set_yticks(np.arange(5))
    ax2.set_yticklabels(guessed_classes, size='small');
    ax2.set_title('Class Probability')
    ax2.set_xlim(0, 1.1)
    plt.tight_layout()
['orange dahlia', 'english marigold', 'gazania', 'osteospermum', 'blanket flower']
['cautleya spicata', 'wallflower', 'red ginger', 'snapdragon', 'siam tulip']
['wild pansy', 'balloon flower', 'silverbush', 'mexican aster', 'clematis']
['hard-leaved pocket orchid', 'anthurium', 'moon orchid', 'bearded iris', 'tiger lily']
In [ ]:
 
In [ ]: